<template>
  <div class="materialPage">
    <div class="tabBar">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="图片" name="1">
          <div class="tags">
            <div v-for="(item, index) in labelList" :key="index" class="tag">
              <el-tag size="large" :effect="item.labelId === currentLabel ? 'dark' : 'plain'" @click="selectTag(item.labelId)">{{ item.labelName }}</el-tag>
              <div v-if="item.labelId === currentLabel" class="action">
                <el-icon size="16" color="#3A68F2" @click="editLabel(item)"><Edit /></el-icon>
                <el-icon size="16" color="#3A68F2" @click="delLabel(item.labelId)"><Delete /></el-icon>
              </div>
            </div>
          </div>
          <div v-if="currentLabel" v-loading="materialLoading">
            <el-divider />
            <div v-if="materialList.length" class="photos">
              <el-card v-for="(item, index) in materialList" :key="index" class="photo">
                <el-image :preview-src-list="[item.image]" :src="item.image" />
                <div class="action">
                  <el-button type="primary" link @click="copyMaterial(item.image)">链接</el-button>
                  <el-button type="primary" link @click="editMaterial(item)">编辑</el-button>
                  <el-button type="danger" link @click="delMaterial(item)">删除</el-button>
                </div>
              </el-card>
            </div>
            <div v-else class="noData">
              <el-empty description="暂无数据" />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="视频" name="2">
          <div class="tags">
            <div v-for="(item, index) in labelList" :key="index" class="tag">
              <el-tag size="large" :effect="item.labelId === currentLabel ? 'dark' : 'plain'" @click="selectTag(item.labelId)">{{ item.labelName }}</el-tag>
              <div v-if="item.labelId === currentLabel" class="action">
                <el-icon size="16" color="#3A68F2" @click="editLabel(item)"><Edit /></el-icon>
                <el-icon size="16" color="#3A68F2" @click="delLabel(item.labelId)"><Delete /></el-icon>
              </div>
            </div>
          </div>
          <div v-if="currentLabel" v-loading="materialLoading">
            <el-divider />
            <div v-if="materialList.length" class="videos">
              <el-card v-for="(item, index) in materialList" :key="index" class="video">
                <video controls="controls" loop="loop">
                  <source :src="item.image" type="video/mp4" />
                </video>
                <div class="action">
                  <el-button type="primary" link @click="copyMaterial(item.image)">链接</el-button>
                  <el-button type="primary" link @click="editMaterial(item)">编辑</el-button>
                  <el-button type="danger" link @click="delMaterial(item)">删除</el-button>
                </div>
              </el-card>
            </div>
            <div v-else class="noData">
              <el-empty description="暂无数据" />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div class="btnBox">
        <el-button type="primary" @click="addLabel">新建标签</el-button>
        <el-button type="primary" @click="addMaterial">上传素材</el-button>
      </div>
    </div>
    <!-- 新增标签 -->
    <el-dialog
      v-model="labelOptions.visible"
      :title="labelOptions.title"
      width="30%"
      center
      :close-on-click-modal="false"
      @closed="labelFormReset"
    >
      <div>
        <el-form ref="labelRef" :model="labelForm" :rules="labelRules">
          <el-form-item label="标签名称">
            <el-input
              v-model="labelForm.labelName"
              maxlength="10"
              placeholder="请输入标签名称"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="labelOptions.visible = false">取 消</el-button>
          <el-button type="primary" :loading="labelLoading" @click="addLabelFn(labelRef)">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 上传素材 -->
    <el-dialog
      v-model="materialOptions.visible"
      :title="materialOptions.title"
      width="30%"
      center
      :close-on-click-modal="false"
      @closed="materialFormReset"
    >
      <div>
        <el-form ref="materialRef" :model="materialForm" :rules="materialRules">
          <el-form-item label="标签选择" prop="labelId">
            <el-tag v-for="(item, index) in labelList" :key="index" size="large" :effect="item.labelId === materialForm.labelId ? 'dark' : 'plain'" @click="onSelect(item.labelId)">{{ item.labelName }}</el-tag>
          </el-form-item>
          <el-form-item label="本地上传" prop="fileList">
            <el-upload
              ref="uploadRef"
              :headers="headers"
              :action="uploadUrl"
              :file-list="materialForm.fileList"
              :limit="limit"
              :accept="activeName === '1' ? accept.photo : accept.video"
              :auto-upload="false"
              :on-change="onChange"
              :before-remove="beforeRemove"
              :on-success="onSuccess"
            >
              <template #trigger>
                <el-button type="primary">点击上传</el-button>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="materialOptions.visible = false">取 消</el-button>
          <el-button type="primary" :loading="materialLoading" @click="addMaterialFn(materialRef)">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="toggleLabelVisible"
      title="更新素材所属标签"
      width="30%"
      center
      :close-on-click-modal="false"
      @closed="toggleLabelReset"
    >
      <div class="tags">
        <div v-for="(item, index) in labelList" :key="index" class="tag">
          <el-tag size="large" :effect="item.labelId === toggleLabelData.labelId ? 'dark' : 'plain'" @click="toggleTag(item.labelId)">{{ item.labelName }}</el-tag>
        </div>
      </div>
      <el-divider />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="toggleLabelVisible = false">取 消</el-button>
          <el-button type="primary" :loading="toggleLoading" @click="toggleLabelConfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { uploadUrl } from '@/utils/request'
import { getToken } from '@/utils/auth'
import {
  tipsGetAll,
  tipsAdd,
  getAllByLabel,
  tipsUpdate,
  tipsDelete,
  saveSource,
  updateSource,
  deleteSource,
} from '@/api/shop'

const activeName = ref('1') // 1图片 2视频
const currentLabel = ref(null)
const labelRef = ref(null)
const labelLoading = ref(false)
const labelOptions = reactive({
  visible: false,
  type: 0, // 0新增 1编辑
  title: '新增标签'
})
const labelForm = reactive({
  labelId: null,
  labelName: ''
})
const labelRules = {
  labelName: [{ require: true, message: '请输入标签名称', trigger: 'blur' }]
}
const labelList = ref([])
const uploadRef = ref(null)
const headers = {
  'Authorization-business': getToken()
}
const limit = 5
const materialRef = ref(null)
const materialLabel = ref(null)
const materialLoading = ref(false)
const materialOptions = reactive({
  visible: false,
  type: 0, // 0新增 1编辑
  title: '上传图片素材'
})
const fileSize = reactive({ // 限制文件大小2MB
  photo: 2,
  video: 20
})
const accept = reactive({
  photo: '.png, .jpeg, .jpg, .webp',
  video: '.mp4, .webm'
})
const materialForm = reactive({
  labelId: null,
  image: '',
  images: [],
  fileList: []
})
const materialRules = {
  labelId: [{ required: true, message: '请选择所属标签', trigger: 'change' }],
  fileList: [{ required: true, message: '请上传素材', trigger: 'change' }]
}
const materialList = ref([])
const toggleLoading = ref(false)
const toggleLabelData = reactive({
  labelId: null,
  image: null
})
const toggleLabelVisible = ref(false) // 修改素材所属标签弹窗

// 获取标签列表
const getLabelList = () => {
  tipsGetAll({
    labelType: activeName.value
  }).then(res => {
    labelList.value = res.data
  })
}
// 获取素材列表
const getMaterialList = () => {
  materialLoading.value = true
  getAllByLabel({
    labelId: currentLabel.value,
    labelType: activeName.value
  }).then(res => {
    materialList.value = res.data
  }).finally(() => {
    materialLoading.value = false
  })
}
// 标签页切换
const handleClick = (tab) => {
  activeName.value = tab.paneName
  labelList.value = []
  materialList.value = []
  currentLabel.value = null
  getLabelList()
}
// 标签点击
const selectTag = (id) => {
  currentLabel.value = id
  getMaterialList()
}
// 点击新增标签
const addLabel = () => {
  labelOptions.visible = true
}
// 点击编辑标签
const editLabel = (row) => {
  labelForm.labelId = row.labelId
  labelForm.labelName = row.labelName
  labelOptions.type = 1
  labelOptions.title = '编辑标签'
  labelOptions.visible = true
}
// 点击删除标签
const delLabel = (id) => {
  if (id === 1) return ElMessage.warning('默认分组不能删除')
  ElMessageBox.confirm('是否确认删除该标签', '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    tipsDelete({
      labelId: id
    }).then(() => {
      ElMessage.success('删除成功')
      currentLabel.value = null
      getLabelList()
    })
  }).catch(() => {})
}
// 新增、编辑标签确认
const addLabelFn = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      labelLoading.value = true
      if (!labelOptions.type) {
        tipsAdd({
          labelName: labelForm.labelName,
          labelType: activeName.value
        }).then(() => {
          ElMessage.success('新增成功')
          labelOptions.visible = false
          getLabelList()
        }).finally(() => {
          labelLoading.value = false
        })
      } else {
        tipsUpdate({
          labelId: labelForm.labelId,
          labelName: labelForm.labelName
        }).then(() => {
          ElMessage.success('修改成功')
          labelOptions.visible = false
          getLabelList()
        }).finally(() => {
          labelLoading.value = false
        })
      }
    } else {
      return false
    }
  })
}
// 标签表单重置
const labelFormReset = () => {
  labelForm.labelId = null
  labelForm.labelName = ''
  labelOptions.title = '新增标签'
  labelOptions.type = 0
}
// 点击上传素材
const addMaterial = () => {
  materialOptions.title = activeName.value === '1' ? '上传图片素材' : '上传视频素材'
  materialOptions.visible = true
}
// 选择素材所属标签
const onSelect = (id) => {
  materialLabel.value = id
  materialForm.labelId = id
}
// 点击编辑素材标签
const editMaterial = (item) => {
  toggleLabelData.labelId = item.labelId
  toggleLabelData.image = item.image
  toggleLabelVisible.value = true
}
// 点击删除素材
const delMaterial = async (row) => {
  ElMessageBox.confirm('是否确认删除该素材', '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    deleteSource({
      labelId: row.labelId,
      image: row.image,
      link: row.link,
      shopId: row.shopId
    }).then(() => {
      ElMessage.success('删除成功')
      getMaterialList()
    })
  }).catch(() => {})
}
// 素材大小校验
const onChange = (file, fileList) => {
  const type = activeName.value === '1' ? '图片' : '视频'
  const size = activeName.value === '1' ? fileSize.photo : fileSize.video
  if (file.size / 1024 / 1024 > size) {
    ElMessage.warning(type + '文件大小不能超过 ' + size + 'MB')
    fileList.splice(fileList.length - 1, 1)
    return
  }
  materialForm.fileList = fileList
}
// 素材删除
const beforeRemove = (file, fileList) => {
  materialForm.fileList = fileList
}
// 确认添加素材
const onSuccess = (file) => {
  materialForm.images.push(file.data.url)
  if (materialForm.images.length === materialForm.fileList.length) {
    saveSource({
      labelId: materialForm.labelId,
      images: materialForm.images
    }).then(res => {
      if (res.code === '') {
        ElMessage.success('新增成功')
        if (currentLabel.value) {
          getMaterialList()
        }
        materialOptions.visible = false
      }
    }).finally(() => {
      materialLoading.value = false
    })
  }
}
// 新增素材确认
const addMaterialFn = (formEl) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      materialLoading.value = true
      uploadRef.value.submit()
    } else {
      return false
    }
  })
}
// 复制素材链接
const copyMaterial = (url) => {
  const input = document.createElement('input')
  document.body.appendChild(input)
  input.setAttribute('value', url)
  input.select()
  if (document.execCommand('copy')) {
    document.execCommand('copy')
  }
  document.body.removeChild(input)
  ElMessage({
    message: '复制链接成功',
    type: 'success',
  })
}
// 选择素材所属标签
const toggleTag = (id) => {
  toggleLabelData.labelId = id
}
// 修改素材所属标签
const toggleLabelConfirm = () => {
  toggleLoading.value = true
  updateSource({
    labelId: toggleLabelData.labelId,
    image: toggleLabelData.image
  }).then(res => {
    if (res.code === '') {
      ElMessage.success('修改成功')
      toggleLabelVisible.value = false
      getMaterialList()
    }
  }).finally(() => {
    toggleLoading.value = false
  })
}
// 清空修改素材所属标签的数据
const toggleLabelReset = () => {
  toggleLabelData.image = null
  toggleLabelData.labelId = null
}
// 素材表单重置
const materialFormReset = () => {
  materialOptions.type = 0
  materialOptions.title = '上传图片素材'
  materialForm.fileList = []
  materialForm.image = ''
  materialForm.images = []
  materialForm.labelId = null
  uploadRef.value.clearFiles()
}
onMounted(() => {
  getLabelList()
})
</script>
<style lang="scss" scoped>
.materialPage {
    padding: 20px;
    margin-top: 20px;
    background-color: #FFFFFF;
    .tabBar {
        padding-top: 10px;
        position: relative;
        .tags {
            display: flex;
            flex-wrap: wrap;
            margin-bottom: 10px;
            .tag {
                display: flex;
                margin-right: 20px;
            }
            .el-tag {
                margin-right: 5px;
                cursor: pointer;
            }
            .action {
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                .el-icon {
                    cursor: pointer;
                }
            }
        }
        .photos,.videos {
            display: flex;
            flex-wrap: wrap;
            .photo,.video {
              margin: 0 20px 10px 0;
            }
            .el-image,video {
                width: 180px;
                height: 180px;
            }
            .noData {
              width: 100%;
              display: flex;
              justify-content: center;
            }
        }
        .btnBox {
            position: absolute;
            top: 0;
            right: 0;
            .el-button {
                height: 38px;
            }
        }
    }
    :deep(.el-dialog) {
        .el-form {
            .el-form-item {
                .el-tag {
                    margin-right: 20px;
                    cursor: pointer;
                }
            }
        }
    }
}
:deep(.el-dialog__body) {
  .tags {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 20px;
    .tag {
        display: flex;
        margin-right: 10px;
    }
    .el-tag {
        margin-right: 5px;
        cursor: pointer;
    }
  }
  .el-form-item {
    .el-form-item__content>div:first-child {
      width: 100%;
    }
  }
}
</style>